import csv
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from loguru import logger


def get_step_name():
    options = webdriver.ChromeOptions()
    browser = webdriver.Chrome(executable_path=ChromeDriverManager(path='../../').install(), options=options)
    browser.implicitly_wait(5)
    browser.get("https://xuat.wxp.woa.com/assistant/caseInputManagement")
    browser.find_element(By.ID, "btn_smartlogin").click()  # oa登录
    time.sleep(1)
    browser.maximize_window()
    browser.get("https://xuc.wxp.woa.com/#/?useCaseId=1&branchType=1&branchId=1&useCaseInstanceVer=144")
    time.sleep(10)
    browser.find_element_by_xpath("//button[contains(text(),'关闭')]").click()
    browser.find_element_by_xpath("//i[contains(text(),'展开所有')]").click()

    num = 1
    label_list = [0]
    while label_list:

        title_value = ''
        label_list = browser.find_elements_by_xpath("//div[@class='virtual-tree-text']")
        for label in label_list:
            title_value = label.text.replace('\n', '')
            logger.info(f'{num}, {title_value}')
            num += 1

            with open("label.csv", "a+", newline="", encoding="utf8") as csvFile:
                csvFileWriter = csv.writer(csvFile)
                csvFileWriter.writerow([title_value])
            if '22.【系统】反馈收款结果' == title_value:
                break
        if '22.【系统】反馈收款结果' == title_value:
            break

        label_list_end = title_value.split(".")[0]
        element = browser.find_element_by_xpath("//span[@class='virtual-tree-text__label' and contains(@title,'%s')]" % label_list_end)
        browser.execute_script("arguments[0].scrollIntoView();", element)
        time.sleep(2)


    browser.quit()


def get_back_step(step_name):
    # 获取该步骤的上一步骤

    # 将步骤标识分隔成列表，方便后面计算它的上一步骤
    a_list = []
    b = ''
    for i in step_name:
        if (b.isdigit() == i.isdigit()) or (b.isalpha() == i.isalpha()):
            b += i
        else:
            a_list.append(b)
            b = i
    a_list.append(b)

    if len(a_list) == 1 and a_list[0] == '1':
        b_list = '最初步骤，无上一步'
    elif a_list[-1].isalpha():    # 步骤标识最后一位是字母时，去掉字母，字母前的编号减1，便为上一步骤标识
        a_list[-2] = str(int(a_list[-2]) - 1)
        b_list = a_list[0:-1]
    elif a_list[-1] == '1':    # 步骤标识最后一位是数字1时，去掉数字1，便为上一步骤标识
        b_list = a_list[0:-1]
    elif a_list[-1].isdigit():    # 步骤标识最后一位是数字时，该数字减1，便为上一步骤标识
        a_list[-1] = str(int(a_list[-1]) -1)
        b_list = a_list
    return ''.join(b_list)


with open("label02.csv", "a+", newline="", encoding="utf8") as csvFile:
    csvFileWriter = csv.writer(csvFile)
    csvFileWriter.writerow(['上一步骤', '当前步骤', '下一步骤'])

with open('label01.csv', 'r', encoding="utf8") as csvfile:
    data = csv.reader(csvfile)
    for i in data:
        step_name = i[0].split('.')[0]

        back_step = get_back_step(step_name)
        print('back_step:', back_step, 'step_name:', step_name)

        if '进入' in i[0]:
            i.append((i[0].split('进入'))[-1])

        i.insert(0, back_step)

        print(i)

        with open("label02.csv", "a+", newline="", encoding="utf8") as csvFile:
            csvFileWriter = csv.writer(csvFile)
            csvFileWriter.writerow(i)
